package com.eedi.framework.info.framework.org;

import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.eedi.framework.common.util.cache.CacheUtils;
import com.eedi.framework.info.service.OrgInfoService;
import com.eedi.framework.org.core.service.OrgFrameworkService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;

/**
 * @author zangy
 */
@Service
public class OrgFrameworkServiceImpl implements OrgFrameworkService {
    @Resource
    OrgInfoService orgInfoService;
    /**
     * 针对 {@link #getOrgInfoIdAndTenantIds()} 的缓存
     */
    private final LoadingCache<Object, List<String>> getOrgInfoIdsCache = CacheUtils.buildCache(
            Duration.ofMinutes(1L),
            // 过期时间 1 分钟
            new CacheLoader<>() {

                @Override
                public List<String> load(Object key) {
                    return orgInfoService.getOrgInfoIdAndTenantIdList();
                }

            });

    /**
     * 针对 {@link # validOrg(String)} 的缓存
     */
    private final LoadingCache<String, Boolean> validOrgInfoCache = CacheUtils.buildCache(
            Duration.ofMinutes(1L),
            // 过期时间 1 分钟
            new CacheLoader<>() {
                @Override
                public Boolean load(String id) {
                    return orgInfoService.validOrg(id);
                }

            });

    @Override
    @SneakyThrows
    public List<String> getOrgInfoIdAndTenantIds() {
        return getOrgInfoIdsCache.get(Boolean.TRUE);
    }

    @Override
    @SneakyThrows
    public void validOrgInfo(String id) {
        validOrgInfoCache.get(id);
    }
}
